<?php

namespace App\Http\Middleware;

use App\Http\Controllers\Admin\Traits\AdminTrait;
use App\Models\Admin\AdminUser;
use Closure,Auth;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenBlacklistedException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;

class AdminRefreshToken extends BaseMiddleware
{
    use AdminTrait;
    protected $auth;

    public function __construct()
    {
        $this->auth = Auth::guard('admin');
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        try {
            $this->checkForToken($request);
        }catch (UnauthorizedHttpException $exception){
            return $this->error(['60004','未登录']);
        }
        try {
            $user_id =  $this->auth->payload()->get('sub');
            $flag = $this->auth->byId($user_id);
            if ($flag){
                $user_info=AdminUser::find($user_id);
                if(!$user_info->status)
                {
                    return $this->error(['60004','账号已被禁用']);
                }
                return $next($request);
            }
            return $this->error(['60004','未登录']);
        }catch (TokenBlacklistedException $exception){
            //当用户退出之后，token就会被拉黑，就会返回TokenBlacklistedException
            return $this->error(['60004','请重新登录']);
        }catch (TokenExpiredException $exception){
            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常，我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
            try {
                // 刷新用户的 token
                $token = $this->auth->refresh();
                // 使用一次性登录以保证此次请求的成功
//                $this->auth->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
                $request->headers->set('Authorization','Bearer '.$token);
            } catch (JWTException $exception) {
                // 如果捕获到此异常，即代表 refresh 也过期了，用户无法刷新令牌，需要重新登录。
                return $this->error(['60004','请重新登录']);
            }
        }catch(JWTException $exception){
            return $this->error(['60004','请重新登录']);
        }

        return $this->setAuthenticationHeader($next($request), $token);
    }
}
